<template>
  <div class='update-avator'>
    <img :src="img" ref="imgRef" />
    <div class="toolBar">
      <div class="cancel" @click="$emit('cancel')">取消</div>
      <div class="confirm" @click="onConfirm">确定</div>
    </div>
  </div>
</template>
<script>
import 'cropperjs/dist/cropper.css';
import Cropper from 'cropperjs';
import { editAvator } from '@/api/user';
export default {
  name: 'UpdateAvatorPage',
  components: {},
  props: {
    img: {
      required: true,
    },
  },
  data() {
    return {
      cropper: null,
    };
  },
  created() {},
  mounted() {
    this.cropper = new Cropper(this.$refs.imgRef, {
      viewMode: 1,
      dragMode: 'move',
      aspectRatio: 1,
      autoCropArea: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false,
      movable: true,
    });
  },
  computed: {},
  methods: {
    onConfirm() {
      // 基于客户端的图片裁切 使用[getCroppedCanvas] 方法
      this.cropper.getCroppedCanvas().toBlob((blob) => {
        console.log(blob);
        const fromData = new FormData();
        fromData.append('photo', blob);
        // toast提示
        this.$toast.loading({
          message: '更新中...',
          forbidClick: true, // 禁用背景点击
          duration: 0, // 展示时长(ms)，值为 0 时，toast 不会消失
        });
        // 调用接口
        editAvator(fromData)
          .then((res) => {
            console.log(res.photo);
            // 成功提示
            this.$toast('更新成功');
            // 更新头像
            this.$emit('update-avator', res.photo);
            // 关闭弹出层
            this.$emit('cancel');
          })
          .catch((err) => {
            this.$toast.fail(err || '更新失败');
            console.log(err);
          });
      });
    },
  },
};
</script>
<style lang='less' scoped>
.update-avator {
  background-color: #000;
  height: 100%;
  img {
    max-width: 100%;
    display: block;
  }
  .toolBar {
    width: 100%;
    position: fixed;
    left: 0;
    bottom: 0;
    display: flex;
    justify-content: space-between;
    font-size: 30px;
    .cancel,
    .confirm {
      width: 100px;
      height: 75px;
      color: #fff;
      line-height: 75px;
      text-align: center;
    }
  }
}
</style>
